<?php
/**
 * exsample for dao in file, and how to use rebuild table name, table dsn lookup
 *
 *
 */
class CtpThread_Dao extends NICED_RealTimeDao
{
    protected $rebuildTableName = false; //if want to dynamic build table name, set this value to true
    protected $lookupDsn = false; //if want to dynamic create table, set this value to true, table dsn lookup will call rebuildTableName  to get table name
    public $app ;
    protected $fields = array("app", "parent", "shard", "type", "sequence", "status", "created", "updated", "creator");

    /**
     * if want to dynamic build table name, override this method
     * can not use $this->getAttr() magic method, will in loop, because of call rebuildTableName in getSQLWrapper function extends from realtime dao
     *
     */
    public function rebuildTableName()
    {
        return $this->tableName."_".$this->getApp();
    }

    public function getApp()
    {
        return $this->app;
    }

    public function setApp($app)
    {
        $this->app = $app;
    }

    /**
     * if want to dynamic create table, override this method
     *
     */
    public function buildUnmappedTableDsn()
    {
        $sql = $this->createTableSQL();
        $rs  = NICED_DBFactory::create($this->dsn)->query($sql);
        return $this->dsn;
    }

    public function formatRow($row)
    {
        $row["username"] = "testing";
        return $row;
    }

    private function createTableSQL()
    { 
        $sql = "CREATE TABLE IF NOT EXISTS {TABLENAME} (
            `id` int UNSIGNED NOT NULL default '0',
            `app` int UNSIGNED NOT NULL default '0',
            `type` int UNSIGNED NOT NULL default '0',
            `parent` bigint UNSIGNED NOT NULL default '0',
            `sequence` int(11) UNSIGNED NOT NULL default '0',
            `creator` int(11) UNSIGNED default '0',
            `created` int UNSIGNED NOT NULL default '0',
            `updated` int UNSIGNED NOT NULL default '0',
            `status` int UNSIGNED NOT NULL default '0',
            PRIMARY KEY  (`parent`,`sequence`),
                  KEY `created` (`parent`, `created`)
              ) ENGINE=InnoDB";

        return str_replace('{TABLENAME}', $this->rebuildTableName(), $sql);
    }
}
